package cn.jsc.order.service.impl;

import cn.jsc.basic.exception.BusinessException;
import cn.jsc.basic.service.impl.BaseServiceImpl;
import cn.jsc.basic.util.CodeGenerateUtils;
import cn.jsc.basic.util.LoginContextUtil;
import cn.jsc.basic.util.PageList;
import cn.jsc.order.domain.AdoptOrder;
import cn.jsc.order.domain.OrderAddress;
import cn.jsc.order.mapper.AdoptOrderMapper;
import cn.jsc.order.mapper.OrderAddressMapper;
import cn.jsc.order.query.AdoptOrderQuery;
import cn.jsc.order.service.IAdoptOrderService;
import cn.jsc.org.domain.Employee;
import cn.jsc.org.mapper.EmployeeMapper;
import cn.jsc.pay.constants.PayConstants;
import cn.jsc.pay.domain.PayBill;
import cn.jsc.pay.mapper.PayBillMapper;
import cn.jsc.pay.service.IPayBillService;
import cn.jsc.pet.domain.Pet;
import cn.jsc.pet.mapper.PetMapper;
import cn.jsc.quartz.constants.JobConstants;
import cn.jsc.quartz.dto.QuartzJobInfo;
import cn.jsc.quartz.service.IQuartzService;
import cn.jsc.user.domain.LoginInfo;
import cn.jsc.user.domain.User;
import cn.jsc.user.domain.UserAddress;
import cn.jsc.user.mapper.UserAddressMapper;
import cn.jsc.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IQuartzService quartzService;

    /**
     * 领养订单的提交
     * @param params
     * @param loginInfo
     * @return
     */
    @Override
    public String adoptOrdersubmit(Map<String, Object> params, LoginInfo loginInfo) {
        //领养宠物id
        long pet_id = Long.parseLong(params.get("pet_id").toString());
        Pet pet = petMapper.loadById(pet_id);
        //1.1宠物下架并设置下架时间 - t_pet - 根据表字段来写
        pet.setState(0);
        pet.setOffsaletime(new Date());
        //1.2.设置领养人
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        pet.setUser_id(user.getId());
        petMapper.update(pet);
        //支付方式
        Long pay_method = Long.parseLong(params.get("pay_method").toString());
        //地址
        Long address_id = Long.parseLong(params.get("address_id").toString());
        //2.1.创建并保存领养订单 - t_order_adopt
        AdoptOrder adoptOrder = petUser2AdoptOrder(pet,user);
        adoptOrderMapper.save(adoptOrder);//自增长的
        //2.2.创建并保存订单地址 - t_order_address
        UserAddress userAddress = userAddressMapper.loadById(address_id);
        OrderAddress orderAddress = userAddress2orderAddress(userAddress,adoptOrder);
        orderAddress.setCreateTime(new Date());
        orderAddressMapper.save(orderAddress);

        //3.1.创建支付单
        PayBill payBill = adoptOrderUser2PayBill(adoptOrder,user,pay_method);
        payBillMapper.save(payBill);
        //3.2.调用支付接口完成支付
        String payData = payBillService.payRequest(payBill);

        //4.创建订单倒计时 - 15分钟未支付就取消订单
        QuartzJobInfo info = new QuartzJobInfo();
        info.setType(JobConstants.OVER_TIME_NO_PAY_ADOPT);
        info.setFireDate(payBill.getLastPayTime());
        info.setJobName(JobConstants.OVER_TIME_NO_PAY_ADOPT+payBill.getUnionPaySn());
        Map<String,Object> map = new HashMap<>();
        map.put("orderId",adoptOrder.getId());
        info.setParams(map);
        //调用添加定时任务方法
        quartzService.add(info);
        System.out.println("订单倒计时取消任务【" + info.getJobName() + "】创建成功...");
        return payData;
    }

    /**
     * 创建支付单
     * @param adoptOrder
     * @param user
     * @param pay_method
     * @return
     */
    private PayBill adoptOrderUser2PayBill(AdoptOrder adoptOrder, User user, Long pay_method) {
        PayBill payBill = new PayBill();
        payBill.setDigest(adoptOrder.getDigest());
        payBill.setMoney(adoptOrder.getPrice());
        payBill.setState(adoptOrder.getState());
        payBill.setLastPayTime(adoptOrder.getLastPayTime());
        payBill.setUnionPaySn(adoptOrder.getPaySn());
        payBill.setShop_id(adoptOrder.getShop_id());//1l

        payBill.setUser_id(user.getId());
        payBill.setNickName(user.getUsername());

        payBill.setPayChannel(pay_method);


        //businessType//哪一种订单
        //businessKey//哪一个订单
        payBill.setBusinessType(PayConstants.BUSINESS_TYPE_ADOPT);//调用支付相关的常量 -领养订单
        payBill.setBusinessKey(adoptOrder.getId());

        return payBill;
    }

    /**
     * 管理员查询领养订单
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<AdoptOrder> admin(AdoptOrderQuery query, HttpServletRequest request) {
        LoginInfo loginInfo = LoginContextUtil.getLoginInfo(request);
        Employee employee = employeeMapper.loadByLoginInfoId(loginInfo.getId());
        query.setShop_id(employee.getShop_id());
        return super.queryData(query);
    }

    /**
     * 用户查询领养订单
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<AdoptOrder> user(AdoptOrderQuery query, HttpServletRequest request) {
        LoginInfo loginInfo = LoginContextUtil.getLoginInfo(request);
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        query.setUser_id(user.getId());
        return super.queryData(query);
    }

    private AdoptOrder petUser2AdoptOrder(Pet pet, User user) {
        AdoptOrder adoptOrder = new AdoptOrder();
        //摘要
        adoptOrder.setDigest("[摘要]对"+pet.getName()+"领养订单！");
        //订单唯一标识
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        adoptOrder.setOrderSn(orderSn);
        //状态
        adoptOrder.setState(0);//待支付
        //领养价-销售价
        adoptOrder.setPrice(pet.getSaleprice());
        //支付唯一标识
        String paySn = CodeGenerateUtils.generateUnionPaySn();
        adoptOrder.setPaySn(paySn);
        //最后支付时间：15分钟之后自动取消
        adoptOrder.setLastPayTime(new Date(System.currentTimeMillis() + PayConstants.ORDER_TIMEOUT));

        //宠物id
        adoptOrder.setPet_id(pet.getId());
        //店铺id
        adoptOrder.setShop_id(pet.getShop_id());
        //领养人id
        adoptOrder.setUser_id(user.getId());
        return adoptOrder;
    }

    private OrderAddress userAddress2orderAddress(UserAddress userAddress, AdoptOrder adoptOrder) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        orderAddress.setOrder_id(adoptOrder.getId());
        orderAddress.setOrderSn(adoptOrder.getOrderSn());
        return orderAddress;
    }
}
